package club.hicode.daydayup.sslFile.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class MyServerHandler_Nio extends ChannelInboundHandlerAdapter {

	private boolean first = true;
	private FileOutputStream fos;
	private BufferedOutputStream bufferedOutputStream;
	private Long length = 0L;

	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		first = true;
		System.out
				.println(ctx.channel().localAddress().toString() + " channelActive" + '-' + System.currentTimeMillis());
	}

	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(
				ctx.channel().localAddress().toString() + " channelInactive" + '-' + System.currentTimeMillis());
		System.out.println("lengthAll:" + length);
		// close stream
		if (bufferedOutputStream != null) {
			bufferedOutputStream.flush();
			bufferedOutputStream.close();
		}
		first = false;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		File file = null;
		// create File
		if (first) {
			System.out.println("create File");
			first = false;
			file = new File("/Volumes/Repository/Others/222.mp4");
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				fos = new FileOutputStream(file);
				//bufferedOutputStream = new BufferedOutputStream(fos);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			return;
		}


		ByteBuf byteBuf = (ByteBuf) msg;
		ByteBuffer nioBuffer = byteBuf.nioBuffer();
		FileChannel channel = fos.getChannel();

		while (nioBuffer.hasRemaining()) {
			channel.write(nioBuffer);
		}
		//channel.close();
		//fos.close();
	}

	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
		//System.out.println(length);
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		// System.out.println("异常信息：\r\n" + cause.getMessage());
		cause.printStackTrace();
	}

}